//
//  WBOAuthViewController.swift
//  WinsonWeibo
//
//  Created by Administrator on 2017/4/18.
//  Copyright © 2017年 Winson. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {


    fileprivate lazy var webView = UIWebView()

    override func loadView() {
        view = webView
        webView.scrollView.isScrollEnabled = false

        // 设置代理
        webView.delegate = self

        // 设置导航栏
        title = "登录新浪微博"

        // 设置返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)

        // 设置自动填充
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 显示微博登录页面
        // 1. 创建url string
        let URLString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"

        // 2. 创建URL
        guard let WBURL =  URL(string: URLString) else {

            return
        }

        // 3. 创建request
        let request = URLRequest(url: WBURL)

        // 4. 加载webView
        webView.loadRequest(request)
    }

    // MARK: - 返回按钮监听方法

    /// 关闭控制器
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }

    // MARK: - 自动填充
    @objc private func autoFill( ){
        // 注入js
        let js = "document.getElementById('userId').value = 'winson_cheung@hotmail.com';" + "document.getElementById('passwd').value = 'chenjiao@520';"

        webView.stringByEvaluatingJavaScript(from: js)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension WBOAuthViewController: UIWebViewDelegate {

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        // 思路：
        // 1. 授权回调地址中必有“https://www.baidu.com”
        print("调用---\(String(describing: request.url?.absoluteString))")

        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {

            return true
        }
        print("query调用---\(String(describing: request.url?.query))")

        // 2. 授权成功后， 回调地址中 查询 “code=”，如果有后面的内容就是授权码， 回调成功将不再显示此页面， 不再加载
        if request.url?.query?.hasPrefix("code=") == false {
            // 授权失败后／或取消授权
            close()

            return false
        }

        // 3. 代码走到此处， 必定有授权码，且包含“code=”， 从juery中获取授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""

        print("授权码--\(code)")
        // 4. 使用授权码获取accessToken
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in

            // 获取失败
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                SVProgressHUD.showInfo(withStatus: "网络请求成功")

                // 1. 发送通知 通知监听者获取到了token
                NotificationCenter.default.post(name: NSNotification.Name(WBUserLogonSuccessedNotification), object: nil)

                // 2. 关闭登录页面
                self.close()
            }
        }
        
        // 4. 拿到授权码后就没有必要继续加载， 直接return false
        return false
    }

    func webViewDidStartLoad(_ webView: UIWebView) {

        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}

